<template>
  <div class="role-manage">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input v-model="searchName" placeholder="请输入角色名称" class="search-input" clearable/>
      <el-select v-model="searchStatus" placeholder="角色状态" class="search-select" clearable>
        <el-option label="全部" value=""/>
        <el-option label="启用" value="1"/>
        <el-option label="禁用" value="0"/>
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAddRole">+ 新增</el-button>
      <el-button>导入</el-button>
      <el-button>导出</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <div class="table-scroll">
      <el-table
          :data="roleList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50"/>
        <el-table-column prop="roleId" label="角色编码" width="100"/>
        <el-table-column prop="roleName" label="名称" width="140"/>
        <el-table-column prop="roleDesc" label="备注"/>
        <el-table-column prop="sort" label="排序" width="80" sortable/>
        <el-table-column prop="userCount" label="授权人数" width="100" sortable/>
        <el-table-column prop="createTime" label="创建时间" width="160" sortable/>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="340" fixed="right">
          <template #default="scope">
            <div class="action-group">
              <el-button link type="primary" @click="handleEditRole(scope.row)">编辑</el-button>
              <el-button link type="primary" @click="handleConfigPermission(scope.row)">分配权限</el-button>
              <el-button link type="primary" @click="handleViewUsers(scope.row)">查看授权用户</el-button>
              <el-button link type="danger" @click="handleDeleteRole(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="pagination-info">共 {{ total }} 条</div>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
      <div class="pagination-goto">
        <span>前往</span>
        <el-input v-model="goToPage" class="goto-input"/>
        <span>页</span>
      </div>
    </div>

    <!-- 角色编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
        width="500px"
    >
      <el-form ref="roleFormRef" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色编码" prop="roleId" v-if="dialogType === 'edit'">
          <el-input v-model="roleForm.roleId" disabled/>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="备注" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc" type="textarea" placeholder="请输入角色描述" :rows="3"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="roleForm.sort" :min="0"/>
        </el-form-item>
        <el-form-item label="授权人数" prop="userCount">
          <el-input-number v-model="roleForm.userCount" :min="0"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="roleForm.status"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitRole">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog
        v-model="permissionDialogVisible"
        title="权限配置"
        width="600px"
    >
      <el-tree
          ref="permissionTree"
          :data="permissionList"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          :props="{ label: 'name', children: 'children' }"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitPermissions">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'

/**
 * 此页面对应权限管理下的 角色管理
 */

// 搜索相关
const searchName = ref('')
const searchStatus = ref('')

// 角色列表數據
const allRoleList = ref([
  {
    roleId: '10001',
    roleName: '系统管理员',
    roleDesc: '',
    sort: 0,
    userCount: 12,
    createTime: '2022-03-15 09:12',
    status: true
  },
  {
    roleId: '10002',
    roleName: '应用管理员',
    roleDesc: '',
    sort: 0,
    userCount: 0,
    createTime: '2022-05-22 11:05',
    status: false
  },
  {
    roleId: '10003',
    roleName: '施工管理员',
    roleDesc: '',
    sort: 0,
    userCount: 2,
    createTime: '2021-12-10 14:30',
    status: true
  },
  {
    roleId: '10004',
    roleName: '分公司管理员',
    roleDesc: '',
    sort: 0,
    userCount: 0,
    createTime: '2023-02-18 16:45',
    status: true
  },
  {
    roleId: '10005',
    roleName: '普通用户',
    roleDesc: '',
    sort: 0,
    userCount: 0,
    createTime: '2022-08-05 08:20',
    status: true
  }
])
const roleList = ref([...allRoleList.value])

// 权限树数据
const permissionList = ref([
  {
    id: 1,
    name: '系统管理',
    children: [
      {
        id: 11,
        name: '用户管理'
      },
      {
        id: 12,
        name: '角色管理'
      },
      {
        id: 13,
        name: '菜单管理'
      }
    ]
  },
  {
    id: 2,
    name: '订单管理',
    children: [
      {
        id: 21,
        name: '订单列表'
      },
      {
        id: 22,
        name: '订单配置'
      }
    ]
  },
  {
    id: 3,
    name: '运单管理',
    children: [
      {
        id: 31,
        name: '待分配运单'
      },
      {
        id: 32,
        name: '已分配运单'
      }
    ]
  }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(50)
const goToPage = ref('')

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const permissionDialogVisible = ref(false)
const checkedPermissions = ref<number[]>([])

// 表单相关
const roleForm = reactive({
  roleId: '',
  roleName: '',
  roleDesc: '',
  sort: 0,
  userCount: 0,
  status: true
})

const rules = reactive({
  roleName: [
    {required: true, message: '请输入角色名称', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
  ],
  roleDesc: [
    {required: true, message: '请输入角色描述', trigger: 'blur'},
    {max: 200, message: '长度不能超过 200 个字符', trigger: 'blur'}
  ],
  sort: [
    {type: 'number', required: true, message: '请输入排序', trigger: 'blur'}
  ],
  userCount: [
    {type: 'number', required: true, message: '请输入授权人数', trigger: 'blur'}
  ]
})

let editIndex = -1

// 多選狀態
const multipleSelection = ref<any[]>([])

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要刪除的角色')
    return
  }
  ElMessageBox.confirm(
      `确认刪除选中的 ${multipleSelection.value.length} 个角色吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    const ids = multipleSelection.value.map(item => item.roleId)
    roleList.value = roleList.value.filter(item => !ids.includes(item.roleId))
    allRoleList.value = allRoleList.value.filter(item => !ids.includes(item.roleId))
    multipleSelection.value = []
    ElMessage.success('刪除成功')
  }).catch(() => {
  })
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 处理角色操作
const handleAddRole = () => {
  dialogType.value = 'add'
  roleForm.roleId = Date.now().toString()
  roleForm.roleName = ''
  roleForm.roleDesc = ''
  roleForm.sort = 0
  roleForm.userCount = 0
  roleForm.status = true
  dialogVisible.value = true
}

const handleEditRole = (row: any) => {
  dialogType.value = 'edit'
  editIndex = roleList.value.findIndex(item => item.roleId === row.roleId)
  roleForm.roleId = row.roleId
  roleForm.roleName = row.roleName
  roleForm.roleDesc = row.roleDesc
  roleForm.sort = row.sort
  roleForm.userCount = row.userCount
  roleForm.status = row.status
  dialogVisible.value = true
}

const handleDeleteRole = (row: any) => {
  ElMessageBox.confirm(
      `确认删除角色"${row.roleName}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 刪除
    roleList.value = roleList.value.filter(item => item.roleId !== row.roleId)
    allRoleList.value = allRoleList.value.filter(item => item.roleId !== row.roleId)
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
  }).catch(() => {
  })
}

const handleSubmitRole = () => {
  if (!roleForm.roleName || !roleForm.roleDesc) {
    ElMessage.warning('請填寫完整信息')
    return
  }
  if (dialogType.value === 'add') {
    // 生成唯一ID已在 handleAddRole 設置
    const now = new Date()
    const pad = (n: number) => n.toString().padStart(2, '0')
    const createTime = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`
    const newRole = {
      roleId: roleForm.roleId,
      roleName: roleForm.roleName,
      roleDesc: roleForm.roleDesc,
      sort: roleForm.sort,
      userCount: roleForm.userCount,
      createTime,
      status: roleForm.status
    }
    roleList.value.push(newRole)
    allRoleList.value.push(newRole)
    ElMessage.success('新增成功')
  } else {
    // 編輯時只更新當前行
    if (editIndex !== -1) {
      Object.assign(roleList.value[editIndex], {
        roleId: roleForm.roleId,
        roleName: roleForm.roleName,
        roleDesc: roleForm.roleDesc,
        sort: roleForm.sort,
        userCount: roleForm.userCount,
        status: roleForm.status
      })
      // 同步 allRoleList
      const allIndex = allRoleList.value.findIndex(item => item.roleId === roleList.value[editIndex].roleId)
      if (allIndex !== -1) {
        Object.assign(allRoleList.value[allIndex], {
          roleId: roleForm.roleId,
          roleName: roleForm.roleName,
          roleDesc: roleForm.roleDesc,
          sort: roleForm.sort,
          userCount: roleForm.userCount,
          status: roleForm.status
        })
      }
      ElMessage.success('修改成功')
    }
  }
  dialogVisible.value = false
}

// 处理权限配置
const handleConfigPermission = (row: any) => {
  checkedPermissions.value = [11, 12, 21] // 示例：默认选中的权限
  permissionDialogVisible.value = true
}

const handleSubmitPermissions = () => {
  // 实现权限保存逻辑
  permissionDialogVisible.value = false
  ElMessage({
    type: 'success',
    message: '权限配置成功'
  })
}

const handleSearch = () => {
  let result = [...allRoleList.value]
  if (searchName.value) {
    result = result.filter(item => item.roleName.includes(searchName.value))
  }
  if (searchStatus.value !== '') {
    result = result.filter(item => String(item.status ? 1 : 0) === searchStatus.value)
  }
  roleList.value = result
}

const handleReset = () => {
  searchName.value = ''
  searchStatus.value = ''
  roleList.value = [...allRoleList.value]
}

const handleViewUsers = (row: any) => {
  // 实现查看授权用户逻辑
}
</script>

<style scoped>
.role-manage {
  padding: 20px;
  background-color: #fff;
}

.search-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.search-input {
  width: 220px;
}

.search-select {
  width: 160px;
}

.toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.table-scroll {
  overflow-x: auto;
}

.el-table {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.pagination-info {
  color: #606266;
}

.pagination-goto {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.goto-input {
  width: 50px;
  margin: 0 8px;
}

:deep(.el-button--primary) {
  --el-button-bg-color: #4066FF;
  --el-button-border-color: #4066FF;
  --el-button-hover-bg-color: #5C7CFF;
  --el-button-hover-border-color: #5C7CFF;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background-color: #4066FF;
  border-color: #4066FF;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table th .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
}

:deep(.el-table__column-filter-trigger) {
  margin-left: 4px;
}

:deep(.el-table th .caret-wrapper) {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-left: 4px;
}

:deep(.el-table th .sort-caret.ascending),
:deep(.el-table th .sort-caret.descending) {
  margin: 0 2px;
}

.action-group {
  display: flex;
  gap: 10px;
  align-items: center;
  white-space: nowrap;
}
</style> 